package model

import (
	"errors"
	"reflect"
)

/*
Model 这里就简单实现model, model还可以更强大:比如添加注册中心
详见: https://gitee.com/go_web_1/server/tree/master/framework/orm/session/model
*/
type Model struct {
	Fields []string
	val    any
}

func (m *Model) ParseModel() error {
	typ := reflect.TypeOf(m.val)
	if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {
		return errors.New("val must be a pointer to struct")
	}
	typ = typ.Elem()
	numFields := typ.NumField()
	for i := 0; i < numFields; i++ {
		f := typ.Field(i)
		m.Fields = append(m.Fields, f.Name)
	}
	return nil
}

func NewModel(val any) (*Model, error) {
	m := &Model{val: val, Fields: make([]string, 0)}
	err := m.ParseModel()
	if err != nil {
		return nil, err
	}
	return m, nil
}
